package com.example.zkweixiu.app.service;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;

import com.example.zkweixiu.app.broadcast.MyBroadcastReveicer;
import com.example.zkweixiu.app.pro.PublicPro;
import com.littlegreens.netty.client.NettyTcpClient;
import com.littlegreens.netty.client.listener.MessageStateListener;
import com.littlegreens.netty.client.listener.NettyClientListener;

import org.greenrobot.eventbus.EventBus;

import java.io.UnsupportedEncodingException;

public class MyService extends Service {
    private NettyTcpClient mNettyTcpClient;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        Log.e("MyService", "服务启动");

        mNettyTcpClient = new NettyTcpClient.Builder()
                .setHost(PublicPro.SERVICE_TCP)    //设置服务端地址
                .setTcpPort(9001) //设置服务端端口号
                .setMaxReconnectTimes(5)    //设置最大重连次数
                .setReconnectIntervalTime(5)    //设置重连间隔时间。单位：秒
                .setSendheartBeat(true) //设置发送心跳
                .setHeartBeatInterval(30)    //设置心跳间隔时间。单位：秒
                //    .setHeartBeatData(new byte[]{0x03, 0x0F, (byte) 0xFE, 0x05, 0x04, 0x0a}) //设置心跳数据，可以是String类型，也可以是byte[]
                //    .setHeartBeatData("I'm is HeartBeatData") //设置心跳数据，可以是String类型，也可以是byte[]，以后设置的为准
                .setIndex(10086)    //设置客户端标识.(因为可能存在多个tcp连接)

                .build();

        mNettyTcpClient.connect();

        mNettyTcpClient.setListener(new NettyClientListener() { //注册监听事件
            @Override
            public void onMessageResponseClient(Object msg, int index) {
                String ponse = msg.toString();
            //    Log.e("onMessageResponseClient", ponse);


                    if (ponse.contains("A1")) {

                    } else if (ponse.length() > 100) {


                        String[] split = ponse.split(",");
                        PublicPro.ac_time.put(split[24], ponse);

                        EventBus.getDefault().post("ok");
                    } else if (ponse.contains("NEW_SET,4005,")) {
                    //    String[] err = ponse.split(",");
                     //   EventBus.getDefault().post("err," + err[2]);
                        EventBus.getDefault().post(ponse);
                    }


            }

            @Override
            public void onClientStatusConnectChanged(int statusCode, int index) {
                Log.e("setListener", String.valueOf(statusCode));
            }
        });
    }

    @SuppressLint("NewApi")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub

        new Thread(new Runnable() {
            public void run() {
            //    Log.e("test", "服务执行");
                //key uuid , 值是ip
                //key s , uuid
                //值 s PublicPro.IP_UUID.get(s) ip
                try {
                    Log.e("MyService", "发送");
                    for (String s : PublicPro.IP_UUID.keySet()) {
                     //   Log.e("test", "CLI_SET,".concat(PublicPro.IP_UUID.get(s)).concat(",").concat(s).concat("&_"));

                        String concat = "CLI_SET,".concat(PublicPro.IP_UUID.get(s)).concat(",").concat(s).concat("&_");
                       // Log.e("CLI_SET",concat);
                        Thread.sleep(600);

                        mNettyTcpClient.sendMsgToServer(concat.getBytes("UTF-8"), new MessageStateListener() {
                            @Override
                            public void isSendSuccss(boolean isSuccess) {
                                if (isSuccess) {
                                     Log.e("isSuccess", "send successful");
                                } else {
                                    Log.e("isSuccess", "设备离线");
                                }
                            }
                        });
                    }
                    //	Log.e("test", s);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    Log.e("test", "出错了");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }).start();

        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent intent2 = new Intent(this, MyBroadcastReveicer.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent2, 0);
        alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000 * 2, pendingIntent);
        return super.onStartCommand(intent, flags, startId);

    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }


    private synchronized void sendService() {


    }


}
